package com.zhoukai.aspectj;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.zhoukai.aspectj.annotation.Log;
import com.zhoukai.aspectj.enums.BusinessStatus;
import com.zhoukai.domain.OperLog;
import com.zhoukai.domain.User;
import com.zhoukai.service.OperLogService;
import com.zhoukai.utils.AddressUtils;
import com.zhoukai.utils.IpUtils;
import com.zhoukai.utils.ServletUtils;
import com.zhoukai.utils.ShiroSecurityUtils;
import io.netty.handler.codec.http.HttpMethod;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.HandlerMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * @Description TODO
 * @Author Mr.ZHOU
 * @Date Created in 2022/1/5 15:29
 */
@Aspect
@Component
@Log4j2
public class OperLogAspect {
    @Autowired
    private OperLogService operLogService;

    // 配置织入点
    @Pointcut("@annotation(com.zhoukai.aspectj.annotation.Log)")
    public void logPointCut() {
        //前提：对象必须被spring管理  只要这个被管理的对象里面的某一个方法上有log注解 就会切入
    }

    /**
     * 处理完请求后执行
     *
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "logPointCut()", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, Object jsonResult) {
        this.handleLog(joinPoint, null, jsonResult);
    }


    /**
     * 拦截异常操作
     *
     * @param joinPoint 切点
     * @param e         异常
     */
    @AfterThrowing(value = "logPointCut()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Exception e) {
        this.handleLog(joinPoint, e, null);
    }

    /**
     * 拦截的核心方法
     *
     * @param joinPoint
     * @param e
     * @param jsonResult
     */
    private void handleLog(JoinPoint joinPoint, Exception e, Object jsonResult) {

        try {
            Log controllerLog = getControllerLog(joinPoint);
            if (controllerLog == null) {
                return;
            }
            // 获取当前的用户
            User loginUser = ShiroSecurityUtils.getCurrentUser();

            // *========数据库日志=========*//
            OperLog operLog = new OperLog();
            operLog.setStatus(String.valueOf(BusinessStatus.SUCCESS.getValue()));
            // 请求的地址
            String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
            operLog.setOperIp(ip);
            String address = AddressUtils.getRealAddressByIP(ip);
            operLog.setOperLocation(address);
            // 返回参数
            operLog.setJsonResult(JSON.toJSONString(jsonResult));
            operLog.setOperUrl(ServletUtils.getRequest().getRequestURI());
            if (loginUser != null) {
                operLog.setOperName(loginUser.getUserName());
            }
            if (e != null) {
                operLog.setStatus(String.valueOf(BusinessStatus.FAIL.getValue()));
                operLog.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000));
            }
            // 设置方法名称
            String className = joinPoint.getTarget().getClass().getName();
            String methodName = joinPoint.getSignature().getName();
            operLog.setMethod(className + "." + methodName + "()");
            // 设置请求方式
            operLog.setRequestMethod(ServletUtils.getRequest().getMethod());
            // 处理设置注解上的参数
            getControllerMethodDescription(joinPoint, controllerLog, operLog);
            //设置操作时间
            operLog.setOperTime(DateUtil.date());
            //保存
            operLogService.insertOperLog(operLog);
        } catch (Exception exp) {
            // 记录本地异常日志
            log.error("==前置通知异常==");
            log.error("异常信息:{}", exp.getMessage());
        }

    }

    /**
     * 处理设置注解上的参数
     *
     * @param joinPoint
     * @param log
     * @param operLog
     */
    private void getControllerMethodDescription(JoinPoint joinPoint, Log log, OperLog operLog) {
        // 设置action动作
        operLog.setBusinessType(String.valueOf(log.businessType().getValue()));
        // 设置标题
        operLog.setTitle(log.title());
        // 设置操作人类别
        operLog.setOperatorType(Integer.valueOf(log.operatorType().getValue()));
        // 是否需要保存request，参数和值
        if (log.isSaveRequestData()) {
            // 获取参数的信息，传入到数据库中。
            setRequestValue(joinPoint, operLog);
        }
    }

    /**
     * 获取参数的信息，传入到数据库中。
     *
     * @param joinPoint
     * @param operLog
     */
    private void setRequestValue(JoinPoint joinPoint, OperLog operLog) {
        String requestMethod = operLog.getRequestMethod();
        if (HttpMethod.PUT.name().equals(requestMethod) || HttpMethod.POST.name().equals(requestMethod)) {
            String params = argsArrayToString(joinPoint.getArgs());
            operLog.setOperParam(StringUtils.substring(params, 0, 2000));
        } else {
            Map<?, ?> paramsMap = (Map<?, ?>) ServletUtils.getRequest().getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
            operLog.setOperParam(StringUtils.substring(paramsMap.toString(), 0, 2000));
        }
    }

    /**
     * 得到切入点上的Log注解
     *
     * @param joinPoint 获取方法上的Log注解的前提是要得到这个方法的Method对象
     * @return
     */
    private Log getControllerLog(JoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        //为什么可强转，。因为我们在使用的时候只在方法上加过这个注解
        MethodSignature methodSignature = (MethodSignature) signature;
        //得到方法对象、
        Method method = methodSignature.getMethod();
        if (method != null) {
            return method.getAnnotation(Log.class);
        }
        return null;
    }

    /**
     * 参数拼装
     */
    private String argsArrayToString(Object[] paramsArray) {
        String params = "";
        if (paramsArray != null && paramsArray.length > 0) {
            for (int i = 0; i < paramsArray.length; i++) {
                if (!isFilterObject(paramsArray[i])) {
                    Object jsonObj = JSON.toJSON(paramsArray[i]);
                    params += jsonObj.toString() + " ";
                }
            }
        }
        return params.trim();
    }

    /**
     * 判断是否需要过滤的对象。
     *
     * @param o 对象信息。
     * @return 如果是需要过滤的对象，则返回true；否则返回false。
     */
    public boolean isFilterObject(final Object o) {
        return o instanceof MultipartFile || o instanceof HttpServletRequest
                || o instanceof HttpServletResponse;
    }
}